import React, { useEffect, useRef, useState } from 'react';
import G6 from '@antv/g6';
import { Modal } from 'antd';
import data from './data.json'

const OrganizationTree = () => {
  const ref = useRef<HTMLDivElement>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedNode, setSelectedNode] = useState<any>(null);

 
  useEffect(() => {
    if (!ref.current) return;

    G6.registerNode(
      'icon-node',
      {
        options: {
          size: [60, 20],
          stroke: '#d9d9d9', // 灰色边框
          fill: '#f5f5f5', // 灰色背景
        },
        draw(cfg: any, group: any) {
          const styles = {
            width: 160,
            height: 60,
            stroke: '#d9d9d9', // 灰色边框
            fill: '#f5f5f5', // 灰色背景
          };

          const { labelCfg = {} } = cfg;

          const w = styles.width;
          const h = styles.height;

          const keyShape = group.addShape('rect', {
            attrs: {
              ...styles,
              x: -w / 2,
              y: -h / 2,
            },
          });

          if (cfg.label) {
            group.addShape('text', {
              attrs: {
                ...labelCfg.style,
                text: cfg.label,
                x: 0,
                y: 0,
                textAlign: 'center',
                textBaseline: 'middle',
              },
            });
          }

          // 添加按钮，只在非叶子节点上添加
          if (cfg.children || cfg._children) {
            group.addShape('circle', {
              attrs: {
                x: 0,
                y: h / 2 - 10,
                r: 10, // 增大按钮半径
                fill: '#1890ff',
                cursor: 'pointer',
              },
              name: 'collapse-button',
            });

            group.addShape('text', {
              attrs: {
                x: 0,
                y: h / 2 - 10,
                textAlign: 'center',
                textBaseline: 'middle',
                text: cfg.collapsed ? '+' : '-',
                fill: '#fff',
                fontSize: 14, // 增大字体大小
                cursor: 'pointer',
              },
              name: 'collapse-text',
            });
          }

          return keyShape;
        },
        update: undefined,
      },
      'rect'
    );

    G6.registerEdge('flow-line', {
      draw(cfg: any, group: any) {
        const startPoint = cfg.startPoint;
        const endPoint = cfg.endPoint;

        const { style } = cfg;
        const shape = group.addShape('path', {
          attrs: {
            stroke: style.stroke,
            endArrow: style.endArrow,
            path: [
              ['M', startPoint.x, startPoint.y],
              ['L', startPoint.x, (startPoint.y + endPoint.y) / 2],
              ['L', endPoint.x, (startPoint.y + endPoint.y) / 2],
              ['L', endPoint.x, endPoint.y],
            ],
          },
        });

        return shape;
      },
    });

    const defaultStateStyles = {};

    const defaultNodeStyle = {
      fill: '#91d5ff',
      stroke: '#40a9ff',
      radius: 5,
    };

    const defaultEdgeStyle = {
      stroke: '#d9d9d9', // 灰色边框
    };

    const defaultLayout = {
      type: 'compactBox',
      direction: 'TB',
      getId: function getId(d: any) {
        return d.id;
      },
      getHeight: function getHeight() {
        return 16;
      },
      getWidth: function getWidth() {
        return 16;
      },
      getVGap: function getVGap() {
        return 50;
      },
      getHGap: function getHGap() {
        return 90;
      },
    };

    const defaultLabelCfg = {
      style: {
        fill: '#000',
        fontSize: 12,
      },
    };

    const container = ref.current;
    const width = container!.scrollWidth;
    const height = container!.scrollHeight || 500;

    const minimap = new G6.Minimap({});

    const graph = new G6.TreeGraph({
      container: container,
      width,
      height,
      linkCenter: true,
      plugins: [minimap],
      modes: {
        default: ['drag-canvas', 'zoom-canvas'],
      },
      defaultNode: {
        type: 'icon-node',
        size: [160, 60],
        style: defaultNodeStyle,
        labelCfg: defaultLabelCfg,
      },
      defaultEdge: {
        type: 'flow-line',
        style: defaultEdgeStyle,
      },
      nodeStateStyles: defaultStateStyles,
      edgeStateStyles: defaultStateStyles,
      layout: defaultLayout,
    });

    graph.data(data);
    graph.render();
    graph.fitView();

    const handleNodeClick = (evt: any) => {
      const { item } = evt;
      const model = item.getModel();
      if (evt.target.get('name') === 'collapse-button' || evt.target.get('name') === 'collapse-text') {
        if (!model.children) {
          model.children = model._children; // 恢复子节点
          model.collapsed = false;
        } else {
          model._children = model.children; // 保存子节点
          model.children = null;
          model.collapsed = true;
        }
        graph.refreshItem(item); // 更新节点以反映更改
        graph.layout();
      } else {
        // 显示弹出层
        setSelectedNode(model);
        setIsModalVisible(true);
      }
    };

    graph.on('node:click', handleNodeClick);
    graph.on('node:touchstart', handleNodeClick); // 添加触摸事件处理

  }, []);

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <div>
      <div ref={ref} style={{ width: '100%', height: '800px' }} />
      <Modal 
        title="个人信息" 
        visible={isModalVisible} 
        onCancel={handleCancel}
        maskClosable={false}  // 禁用点击遮罩层关闭
        footer={null}  // 移除底部按钮
        closable={true}  // 显示右上角关闭按钮
      >
        {selectedNode && (
          <div>
            <p>ID: {selectedNode.id}</p>
            <p>Label: {selectedNode.label}</p>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default OrganizationTree;
